package com.application.Controller;

import it.unipr.ce.dsg.s2p.message.Payload;
import it.unipr.ce.dsg.s2p.org.json.JSONException;
import it.unipr.ce.dsg.s2p.org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import ReadWriteXML.CLearner;


import com.application.DTO.RoleDTO;
import com.application.PhanQuyen.Quyen;
//import com.application.TreeNode.TreeNode;
import ReadWriteXML.CMember;
import ReadWriteXML.CNeighbor;
import ReadWriteXML.CQuestion;
import ReadWriteXML.CResult;
import ReadWriteXML.DOMUltil;
import ReadWriteXML.ReadXML;
import ReadWriteXML.WriteXML;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.application.Activity.FrmLogin;
import com.application.DTO.ClassDTO;
import com.application.DTO.LearnerDTO;
import com.application.DataProvider.AccountDAO;
import com.application.DataProvider.ClassDAO;
import com.application.DataProvider.DetailLearningDAO;
import com.application.DataProvider.LearnerDAO;

public class ReadWriteFileController {
	final private static String SEPARATOR = "/";
	final private static String SEPARATOR1 = "##";
	private static String _fNameListGroup = "ListGroupJoin.txt";
	public static String DIRECTORY = Environment.getExternalStorageDirectory().toString() + "/";
	public static String DIRECTORYMES = DIRECTORY + "MES/";
	public static String DIRECTORYCHAT = DIRECTORY + "MES/CHAT/";
	public static String DIRECTORYCHATPEER = DIRECTORY + "MES/CHAT/PEER/";
	public static String DIRECTORYCHATGROUP = DIRECTORY+ "MES/CHAT/GROUP/";
	public static String DIRECTORYTEST = DIRECTORY + "MES/TEST/";
	public static String DIRECTORYTESTCONTENT = DIRECTORY + "MES/TEST/CONTENT/";

        public static String RULE_BASE_PATH = "ListRule.xml";
	public static String MY_ROLE_PATH = DIRECTORY + "myRole.xml";
	public static String ROLE_SETTING_PATH = DIRECTORY + "mySettingRole.xml";
	public static String ROLE_DEFAULT_PATH = DIRECTORY + "roleMacDinh.xml";
	public static String MEMBER_PATH = DIRECTORY + "memberList.xml";
	public static String TREE_PATH = DIRECTORY + "tree.xml";
	public static String RATING_PATH = DIRECTORY + "ratingList.xml";
	public static String pathNeighborsList = DIRECTORYMES + "NeighborsList.xml";
	public static void WriteDetailLeanrer(String s) {
		String userName = null;
		Document doc = null;

		String[] sTemp = s.split(SEPARATOR);
		CLearner learner = new CLearner();
		learner.set_id(Integer.valueOf(sTemp[0]));
		learner.set_fullName(sTemp[1]);
		learner.set_birthday(sTemp[2]);
		learner.set_address(sTemp[3]);
		learner.set_phone(sTemp[4]);
		learner.set_userName(sTemp[5]);
		learner.set_pass(FrmLogin.get_pass());
		int idclass = Integer.valueOf(sTemp[6]);
		learner.set_idClass(idclass);
		Log.d("PEERDROID", "id class:" + idclass);
		NetworkController.set_idClass(idclass);
		NetworkController.set_idLearner(learner.get_id());
		userName = sTemp[5];

		// cache account xuống file xml
		NetworkController.set_userName(userName);
		String fname = DIRECTORY + userName + ".xml";

		// nếu đã lưu thông tin thì không cần lưu nữa
		if (!ReadWriteFileController.isFile(fname)) {
			Log.d("PEERDROID", "account chua co");
			doc = WriteXML.insertRoot(doc, fname, "LearnerList");
			doc = WriteXML.insertLearner(doc, fname, learner);
		}
		// lưu class vào csdl nếu class chưa tồn tại
		Log.d("PEERDROID", "ghi thông tin class");
		Log.d("PEERDROID", "id class:" + idclass);
		ClassDAO classDao = new ClassDAO(null);
		if (!classDao.isExist(idclass)) {
			Log.d("PEERDROID", "class ko tồn tại");
			ClassDTO classDto = new ClassDTO();
			classDto.set_ID(idclass);
			classDto.set_Name(null);
			classDto.set_Note(null);
			classDao.insertClass(classDto);
		}

	}
	
	
	public static void WriteDetailLeanrerToDB(String s) {

		String[] sTemp = s.split(SEPARATOR);
		LearnerDTO lDto = new LearnerDTO();
		lDto.set_Address(sTemp[3]);
		lDto.set_Fullname(sTemp[1]);
		lDto.set_ID(Integer.valueOf(sTemp[0]));
		lDto.set_IDClass(Integer.valueOf(sTemp[6]));
		lDto.set_Phone(sTemp[4]);
		lDto.set_Username(sTemp[5]);
		lDto.setBirthday(Date.valueOf(sTemp[2]));

		// kiểm tra learner tồn tại chưa, tồn tại rồi thì không cần insert vào nữa
		LearnerDAO lDao = new LearnerDAO(null);
		if (!lDao.isExist(lDto.get_ID())) {
			Log.d("PEERDROID", "learner chua ton tai  " + lDto.toString());
			lDao.insertLearner(lDto);
		}
		NetworkController.set_idClass(lDto.get_IDClass());
		NetworkController.set_idLearner(lDto.get_ID());
		NetworkController.set_userName(lDto.get_Username());
		NetworkController.set_fullName(lDto.get_Fullname());

		// lưu class vào csdl nếu class chưa tồn tại
		ClassDAO classDao = new ClassDAO(null);
		if (!classDao.isExist(lDto.get_IDClass())) {
			Log.d("PEERDROID", "class ko tồn tại");
			ClassDTO classDto = new ClassDTO();
			classDto.set_ID(lDto.get_IDClass());
			classDto.set_Name(null);
			classDto.set_Note(null);
			classDao.insertClass(classDto);
		}

	}

	/**
	 * hàm ghi thông tin nhom
	 * 
	 * @param params
	 * @param fName
	 * @throws IOException
	 */
	public static void WriteDetailGroup(JSONObject params) throws IOException {
		String usernamevip = "";
		String temp = null;
		String[] sArr = null;
		Iterator<String> iter = params.keys();
		Document doc = null;
		// doc = WriteXML.WriteXMLReceive(doc, fName, 1, "CSDL", 123);
		while (iter.hasNext()) {
			String key = (String) iter.next();
			String s = null;
			if (key.contains("keychat")) {
				try {
					usernamevip = params.get(key).toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (key.contains("ds")) {
				try {
					s = params.get(key).toString();
					temp = s;
					sArr = s.split(SEPARATOR1);
					// CQuestion ques = getQuestion(sArr);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		String fName = DIRECTORY + "Group_" + usernamevip + "_grouping_ipList.xml";
		doc = WriteXML.insertRoot(doc, fName, "ListLearner");
		for (int i = 0; i < sArr.length; i++) {
			CMember mem = getMember(sArr[i]);
			doc = WriteXML.insertMember(doc, fName, mem);
		}
		writeTXT(get_fNameListGroup(), "Group_" + usernamevip + "_grouping_Content");
		Log.d("PEERDROID", "da ghi group");
		Log.d("PEERDROID", "da ghi xuong danh sach nhom");
	}

	/**
	 * hàm ghi thông tin update nhom
	 * 
	 * @param params
	 * @param fName
	 */
	public static void WriteUpdateGroup(JSONObject params) {
		String usernamevip = "";
		Iterator<String> iter = params.keys();
		Document doc = null;
		CMember mem = new CMember();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.contains("keychat")) {
				// -----------ghi username---------------
				usernamevip = s;
			}
			if (key.contains("username")) {
				// -----------ghi username---------------
				mem.set_userName(s);
			}
			if (key.contains("fullname")) {
				// -----------ghi fullname---------------
				mem.set_fullName(s);
			}
			if (key.contains("ip")) {
				// -----------ghi ip---------------
				mem.set_ip(s);
			}
			Log.d("PEERDROID", "da ghi group");
		}
		// --------insert member----------------
		String fName = DIRECTORY + "Group_" + usernamevip + "_grouping_ipList.xml";
		doc = ReadXML.BuildXML(fName);
		doc = WriteXML.insertMember(doc, fName, mem);
		Log.d("PEERDROID", "da ghi xuong danh sach nhom");
	}

	public static CMember getMember(String arr) {
		CMember member = new CMember();
		String[] temp = arr.split(SEPARATOR);
		member.set_ip(temp[2].toString());
		member.set_fullName(temp[1].toString());
		member.set_userName(temp[0].toString());
		return member;
	}

	public static String ConcatString(ArrayList<Object> arr) {
		String str = "";
		if (arr.size() != 0) {
			str += arr.get(0);
			int n = arr.size();
			for (int i = 1; i < n; i++) {
				str += "/" + arr.get(i);
			}
		}
		return str;
	}

	public static Payload ReadFeeback(String fName) {
		Payload p = new Payload();
		String path = DIRECTORYTESTCONTENT + fName + ".xml";
		Document doc = null;
		ArrayList<CResult> resList = ReadXML.readResult(doc, path);
		int i = 1;
		for (CResult res : resList) {

			String str = "";
			str += res.getIDQuestion();
			str += SEPARATOR + res.getType();
			switch (res.getType()) {
			case 2: // multi
			{
				for (String s : res.getChoice()) {
					str += SEPARATOR + s;
				}
				break;
			}
			case 4: // nối cột
			{
				for (ArrayList<String> arr_s : res.getPairChoice()) {
					str += SEPARATOR + arr_s.get(0);
					str += SEPARATOR + arr_s.get(1);
				}
				break;
			}
			default: {
				str += SEPARATOR + res.getChoice().get(0);
			}
			}
			p.addParam("" + i, str);
			i++;
		}
		//		CLearner learner;
		//		learner = ReadXML.ReadLearner(NetworkController.get_userName());
		String idDetailLearning = ReadXML.getTextValue(path, "IDDetailLearning");
		String title = ReadXML.getTextValue(path, "Title");
		p.addParam("iddetaillearning", idDetailLearning);
		p.addParam("title", title);
		p.addParam("idlearner", NetworkController.get_idLearner());
		return p;
	}

	public static void WriteExercise(String path, String title, int idExercise, int idPart, int idDetailLearning, long beginTime, long workTime, ArrayList<CQuestion> questionList)
	{
		//nếu file đã tồn tại, xoá file cũ, ghi đè file mới
		if(isFile(path))
			deleteFile(path);
		Document doc = null;
		doc = WriteXML.insertRoot(doc, path, "UsingQuestionList");
		doc = WriteXML.insertTagNode(doc, path, "UsingQuestionList","QuestionList");
		//xem lại nội dung lưu timeLength
		doc = WriteXML.insertValueTagNode(doc, path,"UsingQuestionList", "TimeLength", String.valueOf(workTime));
		doc = WriteXML.insertValueTagNode(doc, path, "UsingQuestionList", "TimeBegin", ConvertTimeToString(beginTime));
		doc = WriteXML.insertValueTagNode(doc, path,"UsingQuestionList", "Title", title);
		doc = WriteXML.insertValueTagNode(doc, path,"UsingQuestionList", "IDDetailLearning", String.valueOf(idDetailLearning));
		doc = WriteXML.insertValueTagNode(doc, path,"UsingQuestionList", "IDPart", String.valueOf(idPart));
		for(CQuestion question:questionList)
			doc = WriteXML.insertQuestion(doc, path, question);
		doc = WriteXML.insertValueTagNode(doc, path, "UsingQuestionList","Count", String.valueOf(questionList.size()));
		doc = WriteXML.insertTagNode(doc, path, "UsingQuestionList","ResultList");
		doc = WriteXML.insertTagNode(doc, path, "UsingQuestionList","ResultTest");
		doc = WriteXML.insertValueTagNode(doc, path, "UsingQuestionList","Status", "1");
	}
	public static void WriteExerciseGroup(String path, String title, int idExercise, int idPart, int idDetailLearning, ArrayList<CQuestion> questionList)
	{
		//nếu file đã tồn tại, xoá file cũ, ghi đè file mới
		if(isFile(path))
			deleteFile(path);
		Document doc = null;
		doc = WriteXML.insertRoot(doc, path, "UsingQuestionList");
		doc = WriteXML.insertTagNode(doc, path, "UsingQuestionList","QuestionList");
		//xem lại nội dung lưu timeLength
		doc = WriteXML.insertValueTagNode(doc, path,"UsingQuestionList", "Title", title);
		doc = WriteXML.insertValueTagNode(doc, path,"UsingQuestionList", "IDDetailLearning", String.valueOf(idDetailLearning));
		doc = WriteXML.insertValueTagNode(doc, path,"UsingQuestionList", "IDPart", String.valueOf(idPart));
		for(CQuestion question:questionList)
			doc = WriteXML.insertQuestion(doc, path, question);
		doc = WriteXML.insertValueTagNode(doc, path, "UsingQuestionList","Count", String.valueOf(questionList.size()));
		doc = WriteXML.insertTagNode(doc, path, "UsingQuestionList","ResultList");
		doc = WriteXML.insertTagNode(doc, path, "UsingQuestionList","ResultTest");
	}
	public static String ConvertTimeToString(long time)
	{
		Log.d("PEERDROID", "time_begin: " + time);
		long time_hour = time /3600;
		Log.d("PEERDROID", "time_hour: " + time_hour);
		long time_min = (time - time_hour*3600) / 60;
		Log.d("PEERDROID", "time_min: " + time_min);
		String strTime = null;
		if(time_min == 0)
			strTime = time_hour + " giờ " + time_min + "0 phút";
		else 
			strTime = time_hour + " giờ " + time_min + " phút";
		return strTime;
	}
	public static long ConvertStringToTime(String time)
	{
		String[] temp = time.split(" ");
		long h = Long.valueOf(temp[0]);
		long m = Long.valueOf(temp[2]);
		long t = h * 3600 + m*60;
		return t;
	}
	public static ArrayList<Integer> WriteTest(JSONObject params, int type) {
		ArrayList<Integer> result = new ArrayList<Integer>();
		ArrayList<CQuestion> questionList = new ArrayList<CQuestion>();
		String path = null;
		String fNameFullTest = null;
		String title = null;
		int idPart = 0;
		int idExercises = 0;
		int idDetailLearning = 0;
		long workTime = 0;
		long beginTime = 0;
		Iterator<String> iter = params.keys();

		while (iter.hasNext()) {

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("idexercises"))
			{
				idExercises = Integer.valueOf(s);
				Log.d("PEERDROID", "idExercies: " + idExercises);
			}
			else if (key.equals("time")) {
				workTime = Long.valueOf(s);
				Log.d("PEERDROID", "workTime: " + workTime);
			}
			else if(key.equals("timebegin"))
			{
				beginTime = Long.valueOf(s);
				Log.d("PEERDROID", "beginTime: " + beginTime);
			}
			else if (key.equals("title")) {
				title = s;
			} 
			else if (key.equals("iddetaillearning")) {
				idDetailLearning = Integer.valueOf(s);
				DetailLearningDAO dlDao = new DetailLearningDAO(null);
				idPart = dlDao.getIDPart(idDetailLearning);
			}

			String[] sArr = s.split(SEPARATOR);
			if (sArr.length > 2) {
				for (String str : sArr)
					Log.d("PEERDROID", str);

				// XuatCauHoi(sArr);
				CQuestion ques = CQuestion.getQuestion(sArr);
				questionList.add(ques);
			}
		}
		//ghi bài tập xuống file
		fNameFullTest = idPart+"_"+idExercises+"_FullTest_"+idDetailLearning;
		path = DIRECTORYTESTCONTENT+fNameFullTest+".xml";
		WriteExercise(path, title, idExercises, idPart, idDetailLearning, beginTime, workTime, questionList);
		
		//ghi thông tin bài tập vào test list
		WriteTestList(idPart, idDetailLearning, title, fNameFullTest);
		result.add(idPart);
		result.add(idExercises);
		result.add(idDetailLearning);
		Log.d("PEERDROID", "thoat write test");
		return result;
	}

	public static void deleteTestList(String path, int idPart, int idDetail, int idExercise)
	{
		Document doc = ReadXML.BuildXML(path);
		if(doc!=null)
		{
			NodeList testList = doc.getElementsByTagName("Test");
			int n = testList.getLength();
			for(int i = 0; i < n; i++)
			{
				Element e = (Element) testList.item(i);
				int idpart = Integer.valueOf(e.getAttribute("IDPart"));
				int iddetail = Integer.valueOf(e.getAttribute("IDDetailLearning"));
				int idexercise = Integer.valueOf(e.getAttribute("IDExercise"));
				if(idpart == idPart && iddetail == idDetail && idexercise ==idExercise)
					e.getParentNode().removeChild(e);
			}
		}
	}
	public static void WriteTestListGroup(int idPart, int idDetailLearning, int idExercise, String title)
	{
		// lưu vào file testList
		String pathTestList = DIRECTORYTEST+"testListGroup.xml";
		Document doc = null;
		doc = WriteXML.insertRoot(doc, pathTestList, "TestList");
		doc = WriteXML.insertValueTagNode(doc, pathTestList,"TestList", "IDPart", String.valueOf(idPart));
		doc = WriteXML.insertValueTagNode(doc, pathTestList,"TestList", "IDDetailLearning", String.valueOf(idDetailLearning));
		doc = WriteXML.insertValueTagNode(doc, pathTestList,"TestList", "IDExercise", String.valueOf(idExercise));
		doc = WriteXML.insertValueTagNode(doc, pathTestList,"TestList", "Title", title);
	}
	public static void ReadTestListGroup(String path)
	{
		
	}
	
	public static void WriteTestList(int idPart, int idDetailLearning, String title, String fnameTest)
	{
		// lưu vào file testList
		String pathTestList = DIRECTORYTEST+"testList.xml";
		Document doc = null;
		File f = new File(pathTestList);
		if (!f.exists())
			doc = WriteXML.insertRoot(doc, pathTestList, "TestList");
		else
			doc = ReadXML.BuildXML(pathTestList);
		//chưa tồn tại thì ghi xuống csdl
		String[] temp = fnameTest.split("_");
		int idExercise = Integer.valueOf(temp[1]);
		ArrayList<Object> attributes = new ArrayList<Object>();
		ArrayList<Object> values = new ArrayList<Object>();
		
		attributes.add("IDDetailLearning");
		attributes.add("IDPart");
		attributes.add("IDExercise");
		values.add(idDetailLearning);
		values.add(idPart);
		values.add(idExercise);
		
		WriteXML.deleteTagElement(doc, pathTestList, "Test", attributes, values);
//		if(!isExistTestInTestList(idPart, idDetailLearning, title, pathTestList))
		WriteXML.insertTestList(doc, pathTestList, title, idPart, idDetailLearning, idExercise, fnameTest);
	}

	public static void UpdateQuestion(CQuestion ques)
	{
		ArrayList<String> ExercisesNameList = new ArrayList<String>();
		String path = DIRECTORYTEST+"testList.xml";
		ArrayList<String> listNameTest = ReadXML.ReadNameExerciseInTestList(path);
		for(String nameTest : listNameTest)
		{
			String pathTest = DIRECTORYTESTCONTENT+nameTest;
			Document doc = null;
			if(isFile(pathTest))
				doc = ReadXML.BuildXML(pathTest);
			if(doc != null)
			{
				ArrayList<Object> attribute = new ArrayList<Object>();
				ArrayList<Object> value = new ArrayList<Object>();
				
				attribute.add("Type");
				attribute.add("ID");
				
				value.add(ques.get_type());
				value.add(ques.get_idQuestion());
				doc = WriteXML.deleteTagElement(doc, path, "Question", attribute, value);
				
				//cập nhật lại câu hỏi trong file
				WriteXML.insertQuestion(doc, pathTest, ques);
			}
			
			
		}
	}
	private static boolean isExistTestInTestList(int idPart, int idDetailLearning, String title, String path)
	{
		Document doc = ReadXML.BuildXML(path);
		if(doc!=null)
		{
			NodeList testList = doc.getElementsByTagName("Test");
			int n = testList.getLength();
			for(int i = 0; i < n; i++)
			{
				Element e = (Element) testList.item(i);
				int idpart = Integer.valueOf(e.getAttribute("IDPart"));
				int iddetail = Integer.valueOf(e.getAttribute("IDDetailLearning"));
				String tit = ReadXML.getTextValue(e, "Title");
				if(idpart == idPart && iddetail == idDetailLearning && tit.equals(title))
					return true;
			}
		}
		return false;
	}
	public static ArrayList<Object> isExistTestInTestList(int idExercises, String path)
	{
		ArrayList<Object> result = new ArrayList<Object>();
		Document doc = ReadXML.BuildXML(path);
		if(doc!=null)
		{
			NodeList testList = doc.getElementsByTagName("Test");
			int n = testList.getLength();
			for(int i = 0; i < n; i++)
			{
				Element e = (Element) testList.item(i);
				int idex = Integer.valueOf(e.getAttribute("IDExercise"));
				if(idex == idExercises)
				{
					result.add(e.getAttribute("IDDetailLearning"));
					result.add(e.getAttribute("IDPart"));
					result.add(e.getAttribute("IDExercise"));
					result.add(ReadXML.getTextValue(e, "Title"));
					result.add(ReadXML.getTextValue(e, "NameTest"));
				}
			}
		}
		return result;
	}
	public static boolean isExistTestInTestList(int idPart, int idDetailLearning)
	{
		String path = DIRECTORY+"testList.xml";
		Document doc = ReadXML.BuildXML(path);
		if(doc!=null)
		{
			NodeList testList = doc.getElementsByTagName("Test");
			int n = testList.getLength();
			for(int i = 0; i < n; i++)
			{
				Element e = (Element) testList.item(i);
				int idpart = Integer.valueOf(e.getAttribute("IDPart"));
				int iddetail = Integer.valueOf(e.getAttribute("IDDetailLearning"));
				if(idpart == idPart && iddetail == idDetailLearning)
					return true;
			}
		}
		return false;
	}

	// public static ArrayList<Integer> WriteTestToDB(JSONObject params, int
	// type)
	// {
	// int time=0;
	// String title = null;
	// int idDetailLearning = 0;
	// ArrayList<Integer> result = new ArrayList<Integer>();
	// int idPart = 0;
	// Iterator<String> iter = params.keys();
	//
	// UsingQuestionListDAO uqlDao = new UsingQuestionListDAO(null);
	//
	// while(iter.hasNext()){
	//
	// String key = iter.next();
	// String s = null;
	// try {
	// s = params.get(key).toString();
	// } catch (JSONException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// if(key.contains("time"))
	// {
	// time = Integer.valueOf(s);
	// }
	// else if(key.contains("title"))
	// {
	// title = s;
	// }
	// else if(key.contains("iddetaillearning"))
	// {
	// idDetailLearning = Integer.valueOf(s);
	// DetailLearningDAO dlDao = new DetailLearningDAO(null);
	// idPart = dlDao.getIDPart(idDetailLearning);
	// }
	// String[] sArr = s.split(SEPARATOR);
	// if(sArr.length>2)
	// {
	// for(String str : sArr)
	// Log.d("PEERDROID",str);
	//
	// QuestionDAO qDao = new QuestionDAO(null);
	// QuestionDTO qDto = new QuestionDTO();
	//
	// TestQuestionDAO tqDao = new TestQuestionDAO(null);
	// TestQuestionDTO tqDto = new TestQuestionDTO();
	//
	// CQuestion ques = CQuestion.getQuestion(sArr);
	// tqDto.set_ID(ques.get_idQuestion());
	// tqDto.set_Content(ques.get_content());
	// //xem lại
	// tqDto.set_IDTestQuestionType(ques.get_type());
	//
	// tqDto.set_QuestionY_N(null);
	//
	// int length = ques.get_listOption().size();//số lượng đáp án
	//
	// if(ques.get_type() == 3)//câu hỏi true false
	// {
	//
	// item = doc.createElement("ListOption");
	// itemChild.appendChild(item);
	//
	// value = doc.createTextNode("null");
	// item.appendChild(value);
	// }
	// else
	// {
	// ArrayList<COption> listOption = new ArrayList<COption>();
	// listOption = question.get_listOption();
	//
	//
	// for(COption option : listOption)
	// {
	// //trường hợp nối cột
	// if(option.get_content() == "")
	// {
	// // Insert child listOption
	// Element e = doc.createElement("ListOption");
	// e.setAttribute("ID", ""+option.get_idDetail());
	// itemChild.appendChild(e);
	//
	// //Insert child key
	// Node item2 = doc.createElement("Key");
	// e.appendChild(item2);
	// // Insert key value
	// value = doc.createTextNode(option.get_key());
	// item2.appendChild(value);
	//
	// //Insert child value
	// item2 = doc.createElement("Value");
	// e.appendChild(item2);
	// // Insert value value
	// value = doc.createTextNode(option.get_value());
	// item2.appendChild(value);
	// }
	// else
	// {
	// // Insert child listOption
	// Element e = doc.createElement("ListOption");
	// e.setAttribute("ID", ""+option.get_idDetail());
	// itemChild.appendChild(e);
	//
	// // Insert value value
	// value = doc.createTextNode(option.get_content());
	// e.appendChild(value);
	// }
	// }
	// }
	// return doc;
	//
	//
	//
	//
	// doc = WriteXML.insertQuestion(doc, path, ques);
	// count++;
	// }
	// }
	// if(flag == true)
	// doc = WriteXML.insertValueTagNode(doc, path,"UsingQuestionList","Title"
	// ,"Test");
	// doc = WriteXML.insertValueTagNode(doc, path,"UsingQuestionList","Count"
	// ,Integer.toString(count));
	// doc = WriteXML.insertTagNode(doc, path,"UsingQuestionList","ResultList");
	// doc = WriteXML.insertTagNode(doc, path,"UsingQuestionList","ResultTest");
	// doc = WriteXML.insertValueTagNode(doc, path, "UsingQuestionList",
	// "Status", "1");
	// //copy sang 1 file khác
	// copyFileXML(doc,pathDec);
	//
	// //xoá file temp
	// deleteFile(path);
	//
	// //lưu vào file testList
	// // String pathTestList = DIRECTORY+"testList.xml";
	//
	// // Document docList = WriteTestList(pathTestList);
	// // ArrayList<Object> attribute = new ArrayList<Object>();
	// // attribute.add("IDPart");
	// // attribute.add("IDDetailLearning");
	// // ArrayList<Object> value = new ArrayList<Object>();
	// // value.add(idPart);
	// // value.add(idDetailLearning);
	// // ArrayList<Object> tagChildNode = new ArrayList<Object>();
	// // tagChildNode.add("UserName");
	// // ArrayList<Object> valueChildNode = new ArrayList<Object>();
	// // valueChildNode.add(NetworkController.get_userName());
	// // WriteXML.insertTagElement(docList, pathTestList, "TestList", "Test",
	// attribute, value, tagChildNode, valueChildNode);
	// // Log.d("PEERDROID","toi da nhan tin mot bai test");
	// result.add(Integer.valueOf(idPart));
	// result.add(idDetailLearning);
	// return result;
	// }



	public static void WriteAccount(String userName, String pass,
			boolean isCheck) {
		Document doc = null;

		String path = DIRECTORY + "account.xml";
		File f = new File(path);
		if (!f.exists()) {
			if (isCheck) {
				doc = WriteXML.insertRoot(doc, path, "Account");
				doc = WriteXML.insertValueTagNode(doc, path, "Account",
						"userName", userName);
				doc = WriteXML.insertValueTagNode(doc, path, "Account", "pass",
						pass);
				// doc = WriteXML.insertValueTagNode(doc, path, "Account",
				// "isCheck", "true");
			}
		} else {
			deleteFile(path);
			if (!isCheck)
				return;
			try {
				doc = WriteXML.insertRoot(doc, path, "Account");
				doc = WriteXML.insertValueTagNode(doc, path, "Account",
						"userName", userName);
				doc = WriteXML.insertValueTagNode(doc, path, "Account", "pass",
						pass);
				// doc = WriteXML.insertValueTagNode(doc, path, "Account",
				// "isCheck", "true");
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

		}
	}

	public static void WriteAccountToDB(String userName, String pass) {
		AccountDAO aDao = new AccountDAO(null);
		if (!aDao.isExist(userName)) {
			aDao.insertAccount(userName, pass);
		}
	}

	public static void updateStatusUsingQuestionList(String path, int status) {
		Log.d("PEERDROID", "path ques: " + path);
		path = ReadWriteFileController.DIRECTORYTESTCONTENT + path + ".xml";
		Document doc = ReadXML.BuildXML(path);
		if (doc != null) {
			// xoá status cũ
			Node nstatus = doc.getElementsByTagName("Status").item(0);
			nstatus.getParentNode().removeChild(nstatus);
			DOMUltil.printDOM(doc);
			// insert status mới
			doc = WriteXML.insertValueTagNode(doc, path, "UsingQuestionList",
					"Status", "" + status);
			DOMUltil.printDOM(doc);
		}
	}

	public static ArrayList<String> ReadAccount(String path) {
		ArrayList<String> acc = new ArrayList<String>();
		File f = new File(path);
		if (f.exists()) {
			String userName = ReadXML.getTextValue(path, "userName");
			String pass = ReadXML.getTextValue(path, "pass");
			// String isCheck = ReadXML.getTextValue(path, "isCheck");
			acc.add(userName);
			acc.add(pass);
			// acc.add(isCheck);
		}
		return acc;
	}

	public static void copyFileXML(String fNameSrc, String fNameDec) {
		Document docSrc = ReadXML.BuildXML(fNameSrc);
		Document docDec = docSrc;
		DOMUltil.writeXmlToFile(fNameDec, docDec);
	}

	public static void copyFileXML(Document docSrc, String fNameDec) {
		Document docDec = docSrc;
		DOMUltil.writeXmlToFile(fNameDec, docDec);
	}

		
	
	 public static void removeLineFromFile(String file, String lineToRemove) {

		    try {

		      File inFile = new File(file);
		      
		      if (!inFile.isFile()) {
		        System.out.println("Parameter is not an existing file");
		        return;
		      }
		       
		      //Construct the new file that will later be renamed to the original filename. 
		      File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
		      
		      BufferedReader br = new BufferedReader(new FileReader(file));
		      PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
		      
		      String line = null;

		      //Read from the original file and write to the new 
		      //unless content matches data to be removed.
		      while ((line = br.readLine()) != null) {
		        
		        if (!line.trim().equals(lineToRemove)) {

		          pw.println(line);
		          pw.flush();
		        }
		      }
		      pw.close();
		      br.close();
		      
		      //Delete the original file
		      if (!inFile.delete()) {
		        System.out.println("Could not delete file");
		        return;
		      } 
		      
		      //Rename the new file to the filename the original file had.
		      if (!tempFile.renameTo(inFile))
		        System.out.println("Could not rename file");
		      
		    }
		    catch (FileNotFoundException ex) {
		      ex.printStackTrace();
		    }
		    catch (IOException ex) {
		      ex.printStackTrace();
		    }
		  }
	
	

	public static boolean isExistUserName(String path, String userName) {
		Log.d("PEERDROID", "vao isExistUserName");
		Document doc = ReadXML.BuildXML(path);
		ArrayList<String> userNameList = ReadXML.getTextValueElement(path,
				"Learner", "UserName");
		Log.d("PEERDROID", "userNameList: " + userNameList);
		Log.d("PEERDROID", "userName: " + userName);
		if (userNameList.indexOf(userName) == -1) // ko tồn tại
			return false;
		return true;

	}

	public static String getFullName(String path, String tagName,String userName) {
		Log.d("PEERDROID","path: " +  path);
		Document doc = ReadXML.BuildXML(path);
		NodeList nlist = doc.getElementsByTagName("Learner");
		String fullName = "";
		int n = nlist.getLength();
		for (int i = 0; i < n; i++) {
			Element e = (Element) nlist.item(i);
			if (e.getAttribute("UserName").equals(userName)) {
				fullName = ReadXML.getTextValue(e, tagName);
				Log.d("PEERDROID","get full name 1: " + fullName);
				break;
			}
		}
		return fullName;
	}


	public static void createFolder(String path)
	{
		File folder = new File(path);
		boolean success = false;
		if(!folder.exists())
		{
			success = folder.mkdir();
		}         
		if (!success) 
		{ 
			// Do something on success
			Log.d("PEERDROID", "tao thu muc thanh cong");
		}
		else 
		{
			// Do something else on failure
			Log.d("PEERDROID", "tao thu muc that bai");
		}
	}

	

	/**
	 * Hàm tạo danh sách các thư mục cần thiết cho ứng dụng
	 */
	public static void createDirectionFolder()
	{
		String path = null;
		//tạo thư mục gốc cho ứng dụng
		path = DIRECTORY + "MES";
		createFolder(path);

		//tạo thư mục chat
		path = DIRECTORY + "MES/CHAT";
		createFolder(path);

		//tạo thư mục chat peer
		path = DIRECTORY + "MES/CHAT/PEER";
		createFolder(path);

		//tạo thư mục chat group
		path = DIRECTORY + "MES/CHAT/GROUP";
		createFolder(path);

		path = DIRECTORY + "MES/TEST";
		createFolder(path);

		path = DIRECTORY + "MES/TEST/CONTENT";
		createFolder(path);

	}

	public static void deleteAllMessChatPeer()
	{
		deleteFolder(DIRECTORYCHATPEER);
	}
	public static void set_fNameListGroup(String _fNameListGroup) {
		ReadWriteFileController._fNameListGroup = _fNameListGroup;
	}

	public static String get_fNameListGroup() {
		return _fNameListGroup;
	}
public static boolean deleteFile(String path) {
		File f1 = new File(path);
		boolean success = f1.delete();
		if (!success) {
			System.out.println("Deletion failed.");
		} else {
			System.out.println("File deleted.");
		}
		return success;
	}

	public static boolean isFile(String path) {
		File f = new File(path);
		return f.exists();
	}
//===========TRUC========================

	/**
	 * Phú Đọc danh sách Quyền từ file
	 * 
	 * @param path
	 *            : Đường dẫn tới file
	 * @return ArrayList<Quyen>
	 */

	public static ArrayList<Quyen> readRule(Context context,String path) {
		ArrayList<Quyen> rs = null;

		//Document doc = ReadXML.BuildXML(path);
		Document doc=ReadXML.buildFromAsset(context, path);

		if (doc != null) {
			rs = new ArrayList<Quyen>();
			NodeList nodeList = doc.getElementsByTagName("Rule");
			int n = nodeList.getLength();
			for (int i = 0; i < n; i++) {
				Element e = (Element) nodeList.item(i);

				boolean read = Boolean.parseBoolean(e.getElementsByTagName("read").item(0).getChildNodes().item(0)
						.getNodeValue());

				boolean write = Boolean.parseBoolean(e.getElementsByTagName("write").item(0).getChildNodes().item(0)
						.getNodeValue());
				boolean send = Boolean.parseBoolean(e.getElementsByTagName("send").item(0).getChildNodes().item(0)
						.getNodeValue());
				boolean receive = Boolean.parseBoolean(e.getElementsByTagName("receive").item(0).getChildNodes()
						.item(0).getNodeValue());

				Quyen quyen = new Quyen(read, write, send, receive, e.getAttribute("ID"), e.getAttribute("Name"));
				rs.add(quyen);

			}
		}

		return rs;
	}

	/**
	 * Phú Đọc danh sách vai trò từ file
	 * 
	 * @param path
	 *            : Đường dẫn tới file
	 *	@param context
	 *			: nếu bằng NULL thì đọc ở file bình thường, khác NULL thì đọc trong thư mục assets
	 * 
	 * @return ArrayList<RoleDTO>
	 */

	public static ArrayList<RoleDTO> readRole(Context context,String path) {
		ArrayList<RoleDTO> rs = new ArrayList<RoleDTO>();
		
		Document doc ;//= ReadXML.BuildXML(path);
		if(context==null){
			doc = ReadXML.BuildXML(path);
		}else{
			doc=ReadXML.buildFromAsset(context, path);
		}
		if (doc != null) {

			rs = new ArrayList<RoleDTO>();
			NodeList roleList = doc.getElementsByTagName("Role");
			if (roleList == null || roleList.getLength() == 0) {
				Log.i("Phu","không có file: "+path);
				return rs;
			}
			int n = roleList.getLength();

			for (int i = 0; i < n; i++) {
				Element element = (Element) roleList.item(i);
				RoleDTO role = new RoleDTO();
				role.setName(element.getAttribute("Name"));

				NodeList ruleList = element.getElementsByTagName("Rule");

				int m = ruleList.getLength();

				for (int j = 0; j < m; j++) {
					Element e = (Element) ruleList.item(j);

					boolean read = Boolean.parseBoolean(e.getElementsByTagName("read").item(0).getChildNodes().item(0)
							.getNodeValue());

					boolean write = Boolean.parseBoolean(e.getElementsByTagName("write").item(0).getChildNodes()
							.item(0).getNodeValue());
					boolean send = Boolean.parseBoolean(e.getElementsByTagName("send").item(0).getChildNodes().item(0)
							.getNodeValue());
					boolean receive = Boolean.parseBoolean(e.getElementsByTagName("receive").item(0).getChildNodes()
							.item(0).getNodeValue());

					Quyen rule = new Quyen(read, write, send, receive, e.getAttribute("ID"), e.getAttribute("Name"));
					role.addRule(rule);

				}
				rs.add(role);
			}
		}		
		return rs;
	}

	/**
	 * Phú Tạo node XML từ 1 quyền
	 * 
	 * @param doc
	 *            : Document
	 * @param rule
	 *            : Quyền
	 * @return Node
	 */
	private static Node createRuleNode(Document doc, Quyen rule) {

		Element e = doc.createElement("Rule");
		e.setAttribute("ID", rule.getID());
		e.setAttribute("Name", rule.getName());

		Node read = doc.createElement("read");
		Node write = doc.createElement("write");
		Node send = doc.createElement("send");
		Node receive = doc.createElement("receive");

		read.setTextContent(rule.getRead().toString());
		write.setTextContent(rule.getWrite().toString());
		send.setTextContent(rule.getSend().toString());
		receive.setTextContent(rule.getReceive().toString());

		e.appendChild(read);
		e.appendChild(write);
		e.appendChild(send);
		e.appendChild(receive);

		return (Node) e;
	}

	/**
	 * Tạo Node XML từ 1 RoleDTO (Vai trò)
	 * 
	 * @param doc
	 *            :Document
	 * @param role
	 *            :Vai trò
	 * @return Node
	 */
	private static Node createRoleNode(Document doc, RoleDTO role) {
		Element e = doc.createElement("Role");
		e.setAttribute("ID", role.getName());
		e.setAttribute("Name", role.getName());
		int n = role.getRuleList().size();

		for (int i = 0; i < n; i++) {
			e.appendChild(createRuleNode(doc, role.getRuleList().get(i)));
		}
		return (Node) e;

	}

	/**
	 * Phú Ghi danh sách Vai trò (RoleDTO) xuống file XML
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param roleList
	 *            : Danh sách vai trò
	 */
	public static void writeRole(String path, ArrayList<RoleDTO> roleList) {
		if (isFile(path))
			deleteFile(path);
		Document doc = null;
		doc = WriteXML.insertRoot(doc, path, "RoleList");

		Log.d("Phu", "root =null" + (doc.getFirstChild() == null));
		for (int i = 0; i < roleList.size(); i++) {
			doc.getFirstChild().appendChild(createRoleNode(doc, roleList.get(i)));
		}
		DOMUltil.writeXmlToFile(path, doc);
		if (isFile(path))
			Log.d("Phu", "writeRole nội dung ptử 0(parse): " + roleList.get(0).toParse());
		else
			Log.d("Phu", "chua ghi" + path);
	}

	/**
	 * Insert 1 vai trò vào 1 file XML có sẵn. Nếu file ko tồn tại thì tạo file
	 * mới
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param role
	 *            : Vai trò
	 */
	public static void insertRole(String path, RoleDTO role) {
		if (isFile(path)) {
			Document doc = ReadXML.BuildXML(path);
			doc.getFirstChild().appendChild(createRoleNode(doc, role));
			DOMUltil.writeXmlToFile(path, doc);
		} else {
			ArrayList<RoleDTO> roleList = new ArrayList<RoleDTO>();
			roleList.add(role);
			writeRole(path, roleList);
		}
	}

	/**
	 * Phú Cập nhật 1 vai trò trong 1 file xml có sẵn (dựa vào tên vai trò)
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param oldRole
	 *            : Vai trò cần cập nhật
	 * @param newRole
	 *            : Vai trò mới
	 */
	public static void updateRole(String path, RoleDTO oldRole, RoleDTO newRole) {		
		Document doc = null;
		doc = DOMUltil.parse(path);		
		NodeList listRole = doc.getElementsByTagName("Role");

		int n = listRole.getLength();
		for (int i = 0; i < n; i++) {
			Element e = (Element) listRole.item(i);
			if (e.getAttribute("Name").equals(oldRole.getName())) {
				e.getParentNode().removeChild(e);
				doc.getFirstChild().appendChild(createRoleNode(doc, newRole));
				break;
			}
		}
		DOMUltil.writeXmlToFile(path, doc);
	}

	/**
	 * Xóa 1 Vai trò trong 1 file XML
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param role
	 *            : Vai trò cần xóa
	 */
	public static void deleteRole(String path, RoleDTO role) {

		Document doc = null;
		doc = DOMUltil.parse(path);
		NodeList listRole = doc.getElementsByTagName("Role");
		int n = listRole.getLength();
		for (int i = 0; i < n; i++) {
			Element e = (Element) listRole.item(i);
			if (e.getAttribute("Name").equals(role.getName())) {
				e.getParentNode().removeChild(e);
				break;
			}
		}
		DOMUltil.writeXmlToFile(path, doc);
	}

	public static ArrayList<CNeighbor> readNeighbor() {
		ArrayList<CNeighbor> listNeighbor = new ArrayList<CNeighbor>();
		ArrayList<CMember> listMember = new ArrayList<CMember>();
		Document _doc = ReadXML.BuildXML(ReadWriteFileController.pathNeighborsList);
		Log.d("PEERDROID", "pathNeighborsList: " + ReadWriteFileController.pathNeighborsList);
		listMember = ReadXML.ReadMember(_doc);
		boolean temp = false;

		for (int i = 0; i < listMember.size(); i++) {
			CMember mem = new CMember();
			mem = listMember.get(i);
			CNeighbor neighbor = new CNeighbor(mem, temp);
			listNeighbor.add(neighbor);
		}
		return listNeighbor;

	}

	public static ArrayList<CMember> readMember(String path) {
		return ReadXML.ReadMember(path);
	}

	/**
	 * Phú Ghi danh sách thành viên xuống file
	 * 
	 * @param path
	 * @param memberList
	 */
	public static void writeMember(String path, ArrayList<CMember> memberList) {
		
		Document doc = null;
		doc = WriteXML.insertRoot(doc, path, "ListLearner");
		Log.d("Phu","writeMember xuống file xml");
		for (int i = 0; i < memberList.size(); i++) {
			doc.getFirstChild().appendChild(createMemberNode(doc, memberList.get(i)));
		}
		DOMUltil.writeXmlToFile(path, doc);
	}

	/**
	 * Phú Insert 1 member xuống file.(Nếu file ko tồn tại thì tạo mới) Nếu
	 * member đã tồn tại thì ko insert
	 * 
	 * @param path
	 * @param member
	 */
	public static void insertMember(String path, CMember member) {		
		if (isFile(path)) {
			ArrayList<CMember> memberList = readMember(path);
			for (CMember m : memberList) {
				if (m.get_userName().equals(member.get_userName()))
					return;
			}
			Document doc = ReadXML.BuildXML(path);
			doc.getFirstChild().appendChild(createMemberNode(doc, member));
			DOMUltil.writeXmlToFile(path, doc);
		} else {
			ArrayList<CMember> memberList = new ArrayList<CMember>();
			memberList.add(member);
			writeMember(path, memberList);
		}
	}

	/**
	 * Phú Xóa 1 member trong file XML dựa vào user name
	 * 
	 * @param path
	 * @param member
	 */
	public static void deleteMember(String path, CMember member) {
		Document doc = null;
		doc = DOMUltil.parse(path);
		NodeList listMember = doc.getElementsByTagName("ListLearner");
		int n = listMember.getLength();
		for (int i = 0; i < n; i++) {
			Element e = (Element) listMember.item(i);
			if (e.getAttribute("UserName").equals(member.get_userName())) {
				e.getParentNode().removeChild(e);
				break;
			}
		}
		DOMUltil.writeXmlToFile(path, doc);
	}

	private static Node createMemberNode(Document doc, CMember member) {
		Element e = doc.createElement("Learner");
		e.setAttribute("UserName", member.get_userName());

		Node ip = doc.createElement("IP");
		Node fullName = doc.createElement("FullName");

		ip.setTextContent(member.get_ip());
		fullName.setTextContent(member.get_fullName());

		e.appendChild(ip);
		e.appendChild(fullName);

		return (Node) e;
	}

	// chat rieng
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}

		// The directory is now empty so delete it
		return dir.delete();
	}

	public static boolean deleteFolder(String path) {
		File f1 = new File(path);
		boolean success = deleteDir(f1);
		if (!success) {
			System.out.println("Deletion failed.");
		} else {
			System.out.println("File deleted.");
		}
		return success;
	}

	public static void writeTXT(String fileName, String content) throws IOException {
		File file = new File(DIRECTORY + fileName);
		boolean exist = file.createNewFile();
		if (!exist) {
			FileWriter fstream = new FileWriter(file, true);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(content + "\r\n");
			out.close();
		} else {
			FileWriter fstream = new FileWriter(file, true);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(content + "\r\n");
			out.close();
			Log.d("PEERDROID", "Da tao file thanh cong");
		}
	}

	public static ArrayList<String> ReadTXT(String path) {
		ArrayList<String> arrMessage = new ArrayList<String>();
		try {
			// Open the file that is the first
			// command line parameter
			if (isFile(path)) {
				FileInputStream fstream = new FileInputStream(path);
				// Get the object of DataInputStream
				DataInputStream in = new DataInputStream(fstream);
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				String strLine;
				// Read File Line By Line
				while ((strLine = br.readLine()) != null) {
					// Print the content on the console
					arrMessage.add(strLine);
				}
				// Close the input stream
				in.close();
			}
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
		return arrMessage;
	}

	public static void writeTXTPath(String path, String content) throws IOException {
		File file = new File(path);
		boolean exist = file.createNewFile();
		if (!exist) {
			FileWriter fstream = new FileWriter(file, true);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(content + "\r\n");
			out.close();
		} else {
			FileWriter fstream = new FileWriter(file, true);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(content + "\r\n");
			out.close();
			Log.d("PEERDROID", "Da tao file thanh cong");
		}
	}

	// end chat rieng

	// Ghi tree node
//	public static void writeTree(ArrayList<TreeNode> treeNodeList) {
//		String path=TREE_PATH;
//		if (isFile(path)) {
//			deleteFile(path);
//		}
//		Document doc = null;
//		doc = WriteXML.insertRoot(doc, path, "ListLearner");
//
//		for (TreeNode node : treeNodeList) {
//			Log.d("Phu", node.getId()+": "+(node.getParentNode() == null ? "-1" : node.getParentNode().getId() + ""));
//			Element e = doc.createElement("Node");
//			e.setAttribute("id", node.getId() + "");
//			e.setAttribute("x", node.getX() + "");
//			e.setAttribute("y", node.getY() + "");
//			e.setAttribute("text", node.getText());
//			e.setAttribute("parentID", (node.getParentNode() == null ? "-1" : node.getParentNode().getId() + ""));
//			e.setAttribute("user", node.getUser());
//			doc.getFirstChild().appendChild(e);
//		}
//		DOMUltil.writeXmlToFile(path, doc);
//	}
//
//	//Insert node
//	public static void insertTreeNode(TreeNode node){
//		String path=TREE_PATH;
//		if (isFile(path)) {
//			
//			Document doc = ReadXML.BuildXML(path);
//			Element e=doc.createElement("Node");
//			e.setAttribute("id", node.getId() + "");
//			e.setAttribute("x", node.getX() + "");
//			e.setAttribute("y", node.getY() + "");
//			e.setAttribute("text", node.getText());
//			e.setAttribute("parentID", (node.getParentNode() == null ? "-1" : node.getParentNode().getId() + ""));
//			e.setAttribute("user", node.getUser());
//			doc.getFirstChild().appendChild(e);
//			DOMUltil.writeXmlToFile(path, doc);
//		} else {
//			TreeNode nodeRoot = new TreeNode(null, "Node gốc", 0, "");
//			ArrayList<TreeNode> treeNodeList = new ArrayList<TreeNode>();
//			treeNodeList.add(nodeRoot);
//			treeNodeList.add(node);
//			writeTree(treeNodeList);
//		}
//	}
//	public static ArrayList<TreeNode> readTree() {
//		String path=TREE_PATH;
//		ArrayList<TreeNode> rs = new ArrayList<TreeNode>();
//		Document doc = ReadXML.BuildXML(path);
//		if (doc != null) {
//			NodeList nodeList = doc.getElementsByTagName("Node");
//			int n = nodeList.getLength();
//			for (int i = 0; i < n; i++) {
//				Element e = (Element) nodeList.item(i);
//				String text = e.getAttribute("text");
//				float x = Float.parseFloat(e.getAttribute("x"));
//				float y = Float.parseFloat(e.getAttribute("y"));
//				int parentID = Integer.parseInt(e.getAttribute("parentID"));
//				TreeNode parentNode= new TreeNode(null, null, parentID, null);
//				int id = Integer.parseInt(e.getAttribute("id"));
//				String user = e.getAttribute("user");
//				TreeNode treeNode = new TreeNode(null, text, x, y, parentNode, id, user);
//				rs.add(treeNode);
//				Log.d("Phu","read: "+id+" "+parentID);
//			}
//		}
//		return rs;
//	}
//	
	
	
	/** An
	 *  Ghi danh sách Đánh giá xuống file XML
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param rating
	 *            : Danh sách Đánh giá
	 */
	public static void writeRating(String path, ArrayList<ArrayList<String>> rating, int count) {
		if (isFile(path))
			deleteFile(path);
		Document doc = null;
		doc = WriteXML.insertRoot(doc, path, "RatingList");

		Log.d("Phu", "root =null" + (doc.getFirstChild() == null));
		for (int i = 0; i < rating.size(); i++) {
			doc.getFirstChild().appendChild(createRatingNode(doc, rating.get(i), count));
		}
		DOMUltil.writeXmlToFile(path, doc);
		if (isFile(path))
			Log.d("Phu", "writeRating nội dung ptử 0(parse): " );
		else
			Log.d("Phu", "chua ghi" + path);
	}
	
	/**An
	 * Tạo Node XML từ 1 ratinglist 
	 * 
	 * @param doc
	 *            :Document
	 * @param ratinglist
	 *            
	 * @return Node
	 */
	private static Node createRatingNode(Document doc, ArrayList<String> ratinglist, int count) {
		Element e = doc.createElement("Rating");
		Log.d("Phu", "Name" + ratinglist.get(0));
		e.setAttribute("Name", ratinglist.get(0));
		float d = Float.parseFloat(ratinglist.get(1));
		float kq = (d*20)/count;
		e.setAttribute("Point", String.valueOf(kq)+" %");
		
		return (Node) e;
	}
	
	/** An
	 * Insert 1 Log vào 1 file XML có sẵn. Nếu file ko tồn tại thì tạo file
	 * mới
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param role
	 *            : Log
	 */
	public static void insertLogFile(String path, String text, String userName) {
		if (isFile(path)) {
			Document doc = ReadXML.BuildXML(path);
			doc.getFirstChild().appendChild(createLogNode(doc, text,userName));
			DOMUltil.writeXmlToFile(path, doc);
		} else {
			
			writeLogFile(path, text,userName);
		}
	}
	
	/** An
	 *  Ghi Log xuống file XML
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param 
	 *            : Danh sách hoạt động
	 */
	public static void writeLogFile(String path, String text, String userName) {
		if (isFile(path))
			deleteFile(path);
		Document doc = null;
		
		doc = WriteXML.insertRoot(doc, path, "LogFile");
		Log.d("Phu", "da tao được Root " );
		doc.getFirstChild().appendChild(createLogNode(doc,text,userName));
		
		DOMUltil.writeXmlToFile(path, doc);
		if (isFile(path))
			Log.d("Phu", "writeRating nội dung ptử 0(parse): " );
		else
			Log.d("Phu", "chua ghi" + path);
	}
	/**An
	 * Tạo Node XML  
	 * 
	 * @param doc
	 *            :Document
	 *
	 *            
	 * @return Node
	 */
	private static Node createLogNode(Document doc, String text, String username) {

        String sDate = getDateTime();
        Log.d("Phu", "Datetime " + sDate);
		Element e = doc.createElement("Action");
		Log.d("Phu", "Name: " + username);
		Log.d("Phu", "da tao được Element " );
		e.setAttribute("on","("+ sDate + ") "+username+ ": " +text);	
		Log.d("Phu", "da tao được Attribute " );
		return (Node) e;
	}
	
	/**An
	 * Lấy thời gian 
	 * 
	 * @param 
	 *            
	 *            
	 * @return String
	 */
	public static String getDateTime(){
		Calendar c = Calendar.getInstance();//Lấy ngày tháng hiện tại
        SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy/HH:mm:ss"); // thiết lập kiểu hiễn thị ngày giờ
        String sDate = df.format(c.getTimeInMillis());// Lấy giờ hiện tại
        Log.d("Phu", "Datetime " + sDate);
		
		/*Calendar c = Calendar.getInstance();
        int month=c.get(Calendar.MONTH)+1;
        String sDate = c.get(Calendar.YEAR) + "-" + month+ "-" + c.get(Calendar.DAY_OF_MONTH) +
        "|" + c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);
        Log.d("Phu", "Datetime " + sDate);*/
        return sDate;
	}
	/**An
	 * Kiểm tra trước khi ghi file 
	 * 
	 * @param 
	 *            
	 *            
	 * @return String
	 */
	public static void checkRuleWriteToLogFile(String text){
		Log.d("Phu", "đã vào checkIsThanhLapNhom: " + text);
		if(NetworkController._peer.account.isThanhLapNhom != true){
			ArrayList<CMember> cmem = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
	        for(int i=0; i<cmem.size(); i++){
	        	
	        	Log.d("Phu","Text: " +text);
	        	String name = NetworkController._peer.getAccount().get_Username();
	        	NetworkController.sendTextLog(cmem.get(i).get_ip(), text, name);
	        }
	        WriteToLogFile(text);
		}else{
			WriteToLogFile(text);
		}
	}
	/**An
	 * Ghi xuống Log file 
	 * 
	 * @param 
	 *            
	 *            
	 * @return String
	 */
	public static void WriteToLogFile(String text){
		
		Log.d("Phu","WriteToLogFile "+ NetworkController._peer.getAccount().get_Username() + "-"+ text );
        String username = NetworkController._peer.getAccount().get_Username();
        String tenNhom = NetworkController.getGroupName();
		Log.d("Phu", "ten nhom 2....: "+ tenNhom);
		String path = ReadWriteFileController.DIRECTORY + tenNhom+"LogList.xml";
		Log.d("Phu", "Path: "+ path);
        ReadWriteFileController.insertLogFile(path, text, username);
	}
	/**An
	 * đọc file Log 
	 * 
	 * @param 
	 *            
	 *            
	 * @return String
	 */
	public static ArrayList<String> readLogFile(Context context,String path) {
		ArrayList<String> rs = new ArrayList<String>();
	
		Document doc = ReadXML.BuildXML(path);
		if (doc != null) {

			rs = new ArrayList<String>();
			NodeList action = doc.getElementsByTagName("Action");
			int n = action.getLength();
			if(n!= 0)
			{
				for(int i=0; i<n; i++)
				{
					Element e = (Element)action.item(i);
					rs.add(e.getAttribute("on"));
				}
			}
		}
		return rs;
	}
	
	public static void deleteTreeNodes(String []idArray){
		String path=TREE_PATH;
		Document doc = null;
		if(doc==null)
			return;
		doc = DOMUltil.parse(path);
		NodeList list = doc.getElementsByTagName("Node");
		int n = list.getLength();
		for(int i=0;i<idArray.length;i++){
			for (int j = 0; j < n; j++) {
				Element e = (Element) list.item(j);
				if (e.getAttribute("id").equals(idArray[i])) {
					e.getParentNode().removeChild(e);
					break;
				}
			}
		}
		DOMUltil.writeXmlToFile(path, doc);
	}
	public static void updateTreeNodeText(String text, int id){
		Log.d("Phu","RW Controller updateTreeNodeText "+id+" "+text);
		String path=TREE_PATH;
		Document doc = null;
		doc = DOMUltil.parse(path);		
		if(doc==null)
			return;
		NodeList listRole = doc.getElementsByTagName("Node");

		int n = listRole.getLength();
		for (int i = 0; i < n; i++) {
			Element e = (Element) listRole.item(i);
			if (e.getAttribute("id").equals(id+"")) {
				
				Element e1=doc.createElement("Node");
				e1.setAttribute("id", id + "");
				e1.setAttribute("x", e.getAttribute("x"));
				e1.setAttribute("y", e.getAttribute("y"));
				e1.setAttribute("text", text);
				e1.setAttribute("parentID", e.getAttribute("parentID"));
				e1.setAttribute("user", e.getAttribute("user"));
				
				
				e.getParentNode().removeChild(e);
				Log.d("Phu","da cap nhat:"+e1.getAttribute("text"));
				doc.getFirstChild().appendChild(e1);
				break;
			}
		}
		DOMUltil.writeXmlToFile(path, doc);
	}
	public static String readTreeText() {		
		StringBuilder builder=new StringBuilder();
		try {
			BufferedReader buff=new BufferedReader(new FileReader(TREE_PATH));
			String line;
			while((line=buff.readLine())!=null){
				builder.append(line);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return builder.toString();
	}
	public static void writeTreeText(String data){
		deleteFile(TREE_PATH);
		try {
			BufferedWriter  writer=new BufferedWriter(new FileWriter(TREE_PATH));
			writer.write(data);
			writer.flush();
			Log.d("Phu","writeTreeText: data="+data);
		} catch (Exception e) {
			Log.d("Phu", "Lỗi trong hàm: writeTreeText "+e.getMessage());
		}
		Log.d("Phu","writeTreeText: "+TREE_PATH);
	
	}
//=============END TRUC================
}
